﻿using System;
using System.Collections.Generic;
using System.Text;

namespace NRadioTray.App.Domain
{
    [Serializable]
    public class Playlist
    {
        private List<Radio> radios;

        public bool IsDirty { get; set; }

        /// <summary>
        /// Gets the radios.
        /// </summary>
        public List<Radio> Radios {
            get
            {
                if (this.radios == null)
                {
                    this.radios = new List<Radio>();                    
                }

                return this.radios;
            }            
        }

        /// <summary>
        /// Adds the radio.
        /// </summary>
        /// <param name="radio">The radio.</param>
        public void AddRadio(Radio radio)
        {
            if( (! this.Radios.Contains(radio)))
            {
                this.Radios.Add(radio);
                this.IsDirty = true;
            }
        }

        /// <summary>
        /// Saves the playlist.
        /// </summary>
        public void SavePlaylist()
        {
            if (this.Radios.Count == 0)
            {
                this.IsDirty = false;
                return;
            }

            this.Save();
            this.IsDirty = false;
        }

        /// <summary>
        /// Loads the playlist.
        /// </summary>
        /// <returns></returns>
        public static Playlist LoadPlaylist()
        {
            var playlist = new Playlist();
            return playlist.Load();
        }

        /// <summary>
        /// Returns a <see cref="System.String"/> that represents this instance.
        /// </summary>
        /// <returns>
        /// A <see cref="System.String"/> that represents this instance.
        /// </returns>
        public override string ToString()
        {
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder
                .AppendFormat("Radios: {0}\n",this.Radios.Count.ToString());

            foreach (var item in this.Radios)
            {
                stringBuilder.AppendLine(item.ToString());
            }

            return stringBuilder.ToString();
        }

        /// <summary>
        /// Saves this instance.
        /// </summary>
        private void Save()
        {
            PlaylistHelper.SerializeToXml<Playlist>(this, "Playlist.xml");
        }

        private Playlist Load()
        {
            if (!System.IO.File.Exists("Playlist.xml"))
            {
                return null;
            }

            return PlaylistHelper.DeserializeFromXml<Playlist>("Playlist.xml");
        }
        
    }
}
